import { getStorage, setStorage } from '@/utils/storage';
import { reqOrderPage } from '@/api/order';

Page({

  data: {
    // 订单列表数据
    orderList: [],
    // 当前页码
    currentPage: 1,
    // 是否正在加载
    isLoading: false,
    // 是否还有更多数据
    hasMore: true
  },

  onLoad() {
    this.loadListOrder()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({ currentPage: 1, hasMore: true });
    this.loadListOrder(true).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 触底加载更多
  onReachBottom() {
    if (!this.data.isLoading && this.data.hasMore) {
      this.setData({ currentPage: this.data.currentPage + 1 });
      this.loadListOrder();
    }
  },

  async loadListOrder(isRefresh = false) {
    if (this.data.isLoading) return
    this.setData({ isLoading: true })

    const token = getStorage('token') || ''
    if (token) {
      const { data } = await reqOrderPage({ wxId: token, currentPage: this.data.currentPage, pageSize: 10 })
      const orderList = isRefresh ? data.records : [...this.data.orderList, ...data.records]
      this.setData({
        orderList, isLoading: false, hasMore: orderList.length < data.total
      })
    }
  },

  // 再来一单
  handleOrderAgain(event) {
    const orderId = event.target.dataset.orderId
    const cart = this.data.orderList.find(item => item.id === orderId).cartResultVO
    setStorage('cart', cart)
    wx.reLaunch({
      url: '../../pages/menu/menu',
    })
  },

  // 查看订单详情
  handleOrderDetail(event) {
    const order = event.currentTarget.dataset.order
    wx.navigateTo({
      url: `./detail/detail?order=${JSON.stringify(order)}`,
    })
  }
})